#include "../Broad_UDP_Server/Broad_UDP_Server.h"

void Broad_UDP_ServerAPI()
{
  //加载Windows环境
  WORD ver = MAKEWORD(2, 2);
  WSADATA dat;
  WSAStartup(ver, &dat);
  
  //创建socket
  SOCKET Server_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  socklen_t optval = 1;
  setsockopt(Server_sock, SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval));
    

  sockaddr_in broadaddr;
  broadaddr.sin_family = PF_INET;
  broadaddr.sin_port = htons(9999); 
  broadaddr.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);


  //调用accept接收客户端连接申请，并将客户端信息保存至Client_sin中
  sockaddr_in Client_sin = {};
  char IPdotdec[20];
  int nAddrLen = sizeof(sockaddr_in);

  char recvBuf[1024] = {};
  while (true)
  {
    printf("Please input:\n");
    scanf_s("%s",recvBuf,sizeof(recvBuf));

    sendto(Server_sock,recvBuf, strlen(recvBuf), 0, (SOCKADDR*)&broadaddr, sizeof(SOCKADDR)); 

    memset(recvBuf, 0, sizeof(recvBuf));
  }

  //当客户端断开连接后，会关闭客户端
  closesocket(Server_sock);
  //
  WSACleanup();
  printf("Sever closed ...");
}